<template>
	<div class="postManagement" curPageName="postman123456789">
		<layoutContent  >
			<template #left>
				<treeNode :defTreeValue="org_ids" :treeLevel="2" @node-change="nodeChange"></treeNode>
			</template>
			<template #right>
				<!-- 搜索模块儿 -->
				<div>

					<serachBar custom_class="myclass" :placeholder="$t('organization_postManagement.post_title')"
						:close-advanced=true :search_val=state.key_words @searchEvent="searchFn">
						<template #header>
							<div>
								<!-- <el-cascader style="min-width: 240px;"
								:placeholder="$t('organization_postManagement.company_department')"
								v-model="state.comDep" :options="depArr" filterable :props="propsTwo" clearable
								@change="handleChangeSearch" /> -->
							</div>
						</template>
						<template #footer>
							<el-button type="primary" v-auth="{'authArr':authArr,'key':'postAdd'}"
								@click="onPlus">{{$t("organization_postManagement.add_post_title")}}</el-button>
						</template>
					</serachBar>
				</div>
				<div class="merak-table-wrapper">
					<MerakXTable ref="tableRef" v-bind="tablePayload" :query-columns="handleQueryColumns"
						:query-data="handleQueryData">

						<template #handler="{ row }">
							<div style="display: flex;">
								<el-button v-auth="{'authArr':authArr,'key':'postEdit'}" type="primary" link
									@click="saveEdit(row)">
									{{$t("merak.edit")}} </el-button>
								<el-button v-auth="{'authArr':authArr,'key':'merge'}" type="primary" link
									@click="merge(row)">
									{{$t("merak.merge")}} </el-button>

								<el-button v-auth="{'authArr':authArr,'key':'postDel'}"
									:type="row.person_count?'':'danger'" link :disabled="row.person_count>0"
									@click="delCompany(row)"> {{$t("merak.delete")}}
								</el-button>
							</div>
						</template>

					</MerakXTable>
				</div>
			</template>
		</layoutContent>



		<!-- 弹窗模块儿 -->
		<div class="drawer">

			<el-drawer modal-class="merak_modal" v-model="drawerStation" direction="rtl" :close-on-click-modal="false"
				:close-on-press-escape="false" size="600">
				<template #header>
					<div class="merak_modal_title">{{stationTitle}}</div>
				</template>
				<div>
					<el-form :model="stationForm" ref="stationRef" :rules="stationRules" label-position="top">

						<el-form-item :label="$t('organization_departmentManagement.dep_company')" prop="company">
							<el-select class="qf_select" style="width: 100%;" filterable v-model="stationForm.company"
								@change="getDepFun">
								<el-option v-for="cItem in orgAll.company" :key="cItem.value" :label="cItem.label"
									:value="cItem.value" />
							</el-select>
						</el-form-item>

						<el-form-item :label="$t('organization_postManagement.postDep')" prop="department">
							<!--  -->
							<el-select class="qf_select" style="width: 100%;" :disabled="!stationForm.company"
								filterable v-model="stationForm.department">
								<el-option v-for="cItem in orgAll.departments[stationForm.company]" :key="cItem.value"
									:label="cItem.label" :value="cItem.value" />
							</el-select>
						</el-form-item>



						<el-form-item :label="$t('organization_postManagement.title_cn')" prop="title_cn">
							<el-input class="qf_input" v-model="stationForm.title_cn" />
						</el-form-item>

						<el-form-item :label="$t('organization_postManagement.title_ru')" prop="title_ru">
							<el-input class="qf_input" v-model="stationForm.title_ru" />
						</el-form-item>

						<el-form-item :label="$t('organization_postManagement.job_requirements_cn')">
							<el-input class="qf_textare" type="textarea" maxlength="1000"
								:autosize="{ minRows: 6, maxRows: 15 }" show-word-limit
								v-model="stationForm.job_requirements_cn" />
						</el-form-item>

						<el-form-item :label="$t('organization_postManagement.job_requirements_ru')">
							<el-input class="qf_textare" type="textarea" maxlength="1000"
								:autosize="{  minRows: 6, maxRows: 15 }" show-word-limit
								v-model="stationForm.job_requirements_ru" />
						</el-form-item>




					</el-form>

				</div>

				<template #footer>
					<el-button type="default" @click="cancelEmpty(stationRef)">{{$t("merak.cancel")}}</el-button>
					<el-button type="primary" plain v-if="editShow" :loading="loadingState"
						@click="saveContinue('2',stationRef)">{{$t("merak.save_continue")}}</el-button>
					<el-button type="primary" @click="submitForm('1',stationRef)"
						:loading="loadingState">{{$t("merak.save")}}</el-button>

				</template>
			</el-drawer>


			<!-- 合并 -->
			<el-dialog modal-class="merak_modal" v-model="mergeStation" direction="rtl" :close-on-click-modal="false"
				:close-on-press-escape="false" width="450">
				<template #header>
					<div class="merak_modal_title">{{mergeTitle}}</div>
				</template>
				<div class="companyPad">
					<el-form :model="mergeForm" ref="mergeRef" label-width="auto" :rules="mergeRules"
						label-position="top">
						<el-row :gutter="20">

							<el-col :span="24">
								<el-form-item :label="$t('organization_postManagement.old_post_title')">
									<span class="label_show">{{mergeForm.old_org_title}}</span>

								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">

							<el-col :span="24">
								<el-form-item :label="$t('organization_postManagement.merge_to')"
									prop="new_org_title_id">
									<el-select class="qf_select" style="width: 100%;" filterable
										v-model="mergeForm.new_org_title_id">
										<el-option v-for="cItem in postList" :key="cItem.key" :label="cItem.value"
											:value="cItem.key" />
									</el-select>

								</el-form-item>
							</el-col>
						</el-row>



					</el-form>

				</div>

				<template #footer>
					<el-button type="default" @click="merakCancel(mergeRef)">{{$t("merak.cancel")}}</el-button>
					<el-button type="primary" @click="merakConfirm(mergeRef)"
						:loading="loadingState">{{$t("merak.confirm")}}</el-button>

				</template>
			</el-dialog>
		</div>

	</div>


</template>

<script setup lang="ts" name="companyManagement">
	import layoutContent from "@/components/LayoutComponents/index.vue";
	import type { CascaderProps } from 'element-plus';
	import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';
	import { ref, reactive, computed, getCurrentInstance, nextTick, onMounted } from "vue";
	import serachBar from "@/components/SearchBar/index";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import { getAlltree } from "@/minxins/useOrgsStore";//获取组织架构树
	import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
	import { Path, getTableColumns, getTableData } from "@/api/modules/table";
	import useLoading from "@/hooks/useLoading";
	import { useOraStore } from "@/stores/modules/oragnization";
	import { getLocationParams } from "@/utils/index";
	// 使用队列 loading 管理初始化页面加载状态
	const { queueLoading, queueId } = useLoading();
	const oraStore = useOraStore();
	import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getOrgsListApi, getOrgsStationTableListApi, saveOrgsStationApi, delOrgsStationApi, getOrgDepTitleApi, saveMergeApi, getInitOrgsApi } from "@/api/modules/personalManagementApi/organization";

	const tableRef = ref < MerakXTableInstance > ();

	//初始化级联 公司部门
	let companyDep = ref([]);
	let comDepBool = ref(false);



	//#region 树节点点击
	const org_ids = ref(0);
	const parentNodeId=ref(0);
	//接收url参数
	const newUrl = new URL(window.location.href);
	let url_org_id = getLocationParams(newUrl.href, 'org_id');
	org_ids.value = Number(url_org_id) ?? 0;
	let parent_id = getLocationParams(newUrl.href, 'parent_id');
    parentNodeId.value=Number(parent_id)??0;
	const nodeChange = (data: any) => {
		// console.log(data, "树节点值，，，，")
		let { org_id, level,parent_id } = data;
		// 构建新的URL
		const newUrl = new URL(window.location.href);
		newUrl.searchParams.set('org_id', org_id);
		newUrl.searchParams.set('parent_id', parent_id);

		org_ids.value = org_id;
		parentNodeId.value=parent_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());
		state.level = level;
		state.org_id = org_id == 0 ? '' : org_id;

	}

	//#endregion

	//#region 表单编辑

	const stationRef = ref();
	let loadingState = ref(false);
	const { proxy } = getCurrentInstance();
	let stationTitle = ref(proxy.$t("organization_postManagement.add_post_title"));
	let drawerStation = ref(false);
	let editShow = ref(true);
	//表单参数结构
	const stationForm = ref({});
	const stationRules = reactive({
		company: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		department: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		title_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		title_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		// job_requirements_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		// job_requirements_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
	});

	//保存并添加
	const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
		submitForm(typebtn, formEl)
	}
	//保存

	const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				//保存
				loadingState.value = true;
				saveOrgsStationApi(stationForm.value).then(res => {
					console.log(res);
					loadingState.value = false;
					if (res.code == ResultEnum.SUCCESS) {
						getAlltree();//初始化组织架构
						successMsg(proxy.$t("merak.action_success"));
						if (typebtn == 1) {
							//关闭弹窗
							drawerStation.value = false;

						}

						companyDep.value = [];
						comDepBool.value = false;
						nextTick(() => {
							comDepBool.value = true;
							stationForm.value = resetForm();
							formEl.resetFields();
						})

						tableRef.value?.reloadData();
						return;
					} else {
						failMsg(res.message)
					}
					// if (res.code == ResultEnum.ERROR) {

					// }
				})
			} else {
				console.log("error submit!", fields);
			}
		});
	};


	//删除
	const delCompany = (rows) => {
		delConfimMsg({
			callback: val => {
				if (val == "confirm") {
					delOrgsStationApi({ org_title_id: rows.org_title_id }).then(res => {
						if (res.code == ResultEnum.SUCCESS) {
							successMsg(proxy.$t("merak.delete_success"));
							tableRef.value?.reloadData();
							return;
						}
						if (res.code == ResultEnum.ERROR) {
							failMsg(res.message)
						}

					})
				}
			}
		});
	}

	//编辑
	const saveEdit = (rows) => {


		let { org_title_id, company, department, title_cn, title_ru, job_requirements_cn, job_requirements_ru } = JSON.parse(JSON.stringify(rows));;
		stationRef.value?.resetFields();
		companyDep.value = [];
		companyDep.value.push(company);
		companyDep.value.push(department);


		stationForm.value = {
			org_title_id: org_title_id,
			department: department,//部门
			company: company,//公司
			title_cn: title_cn,//组织名称(中文)
			title_ru: title_ru,//组织名称(俄文)
			job_requirements_cn: job_requirements_cn,//岗位要求
			job_requirements_ru: job_requirements_ru,//岗位要求
		};
		//打开弹窗
		comDepBool.value = false;
		nextTick(() => {
			comDepBool.value = true;
			drawerStation.value = true;
		})

		editShow.value = false;
		stationTitle.value = proxy.$t("organization_postManagement.edit_post_title");
	}
	//取消
	const cancelEmpty = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		drawerStation.value = false;
	}
	//新增
	const onPlus = () => {
		companyDep.value = [];

		comDepBool.value = false;
		nextTick(() => {
			comDepBool.value = true;
		})

		drawerStation.value = true;
		editShow.value = true;
		stationTitle.value = proxy.$t("organization_postManagement.add_post_title");
		companyDep.value = "";//清空级联
		stationForm.value = resetForm();
	}

	const resetForm = () => {

		stationRef.value?.resetFields();
		return {
			org_title_id: 0,
			department: org_ids.value,//部门
			company: parentNodeId.value,//公司
			title_cn: "",//组织名称(中文)
			title_ru: "",//组织名称(俄文)
			job_requirements_cn: "",//岗位要求
			job_requirements_ru: "",//岗位要求
		}
	}



	//#endregion


	//#region 合并
	const mergeRef = ref();
	const postList = ref();//当前部门下的所有岗位
	const mergeStation = ref(false);
	const mergeTitle = ref("合并岗位");
	const mergeForm = ref({ new_org_title_id: '' })

	const mergeRules = reactive({
		new_org_title_id: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }]
	});


	//合并打开
	const merge = (row) => {
		console.log(row, "合并、。。。。")
		let { company, department, title_cn, title_ru, org_title_id } = row;
		getDepPostList(org_title_id, company)
		let old_org_title = title_ru;
		if (proxy.$t("lang") == 'zh') {
			old_org_title = title_cn;
		}
		mergeStation.value = true;
		mergeForm.value = {
			new_org_title_id: '',
			depId: department,
			old_org_title_id: org_title_id,
			old_org_title: old_org_title,

		}
	}

	//获取当前部门下的所有岗位
	const getDepPostList = (org_id, companyId) => {
		getOrgDepTitleApi({ org_title_id: org_id, company: companyId }).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;
				postList.value = data;
				console.log(data, "当前部门下的岗位")
			}
		})
	}
	//baocun 

	const merakConfirm = async (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				//保存
				loadingState.value = true;
				saveMergeApi(mergeForm.value).then(res => {
					console.log(res);
					loadingState.value = false;
					if (res.code == ResultEnum.SUCCESS) {
						getAlltree();//初始化组织架构
						successMsg(proxy.$t("merak.action_success"));
						mergeStation.value = false;


						tableRef.value?.reloadData();
						return;
					} else {
						failMsg(res.message);;
					}
					// if (res.code == ResultEnum.ERROR) {
					// 	failMsg(res.message);;

					// }
				}).catch(err => {
					loadingState.value = false;
				})
			} else {
				console.log("error submit!", fields);

			}
		});
	}
	//取消
	const merakCancel = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		mergeStation.value = false;
	}
	//#endregion

	//#region 列表


	// 页面配置数据
	let authArr = ref({});
	const state = reactive < {
		key_words: string,
		level: string,
		org_id: string,
		comDep: Array,
		columnType: Object
	} > ({
		key_words: '',
		level: '',
		org_id: '',//职务名称
		comDep: [],
		columnType: {}
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({ key_words: state.key_words, org_id: state.org_id, level: state.level }));
	const columnTypeNew = computed(() => ([].concat(state.columnType)))

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "org_title_id",
		// 初始化的外部筛选数据
		params,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		//导出
		enabledExport: false,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		columnType: columnTypeNew,

		// columnType: ['selection',"multiple", "handle"],
		// 批量操作选项
		batches: [{ type: "delete", text: "批量删除", color: "red" }],
		// 操作列选项
		// handles: [{ type: "delete", text: "删除", color: "red" }]
	});

	//获取数据

	//查询
	let search_val = ref("");
	const searchFn = (e) => {
		state.key_words = e.search;
	}

	//初始化搜索公司部门
	const propsTwo: CascaderProps = {
		label: 'title',
		value: 'org_id',
		children: 'children'
	}

	//列表内容展示区
	const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
		const params: Record<string, any> = {};
		if (!!page) {
			Object.assign(params, { ...page }, from);
		}
		return await getOrgsStationTableListApi(params).then(res => {
			//  ========权限判断 start  ======
			let authList = res?.auth_list;
			if (authList) {
				authArr.value = authList;
				if (authList?.postEdit.show || authList?.postDel.show || authList?.merge.show) {
					state.columnType = { type: 'handle', width: proxy.$t("lang") == 'zh' ? 150 : 250, slot: 'handler' };
				}
				tablePayload.enabledExport = !!res?.auth_list?.export?.show;
			}
			// ========权限判断 end  ======
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;
				const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

				return table_data;
			}
		})

	};


	// 获取表头数据
	const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
		// 初始化接口需要传入队列 loading 暴露的 id
		return getTableColumns(Path.orgsStations, queueId.value).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							// 匹配列字段用于扩展自定义
							case "title_cn":
							case "title_ru":
								// 固定列
								column.fixed = "left";
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};
	//#endregion



	//#region  初始化接口


	//#region 初始化级联 公司部门 

	const props: CascaderProps = {
		label: 'title',
		value: 'org_id',
		children: 'children'
	}
	// const handleChange = (val) => {
	// 	stationForm.value.company = "";
	// 	stationForm.value.department = "";
	// 	if (val) {
	// 		stationForm.value.company = val[0];
	// 		stationForm.value.department = val[1];
	// 	}
	// 	// console.log(e[0], "第一个节点选择")
	// }


	const getDepFun = (val) => {
		stationForm.value.department = "";
	}
	//#endregion



	const orgAll = ref([]);//
	onMounted(() => {

		getInitOrgsApi().then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				orgAll.value = res.data;
			} else {
				failMsg(res.message);;
			}
		})
	})
	//#endregion
</script>

<style scoped lang="scss">
	@import "./index.scss";
</style>